<template>
  <div class="video-detail-container">
    <div class="video-main">
      <div class="left-container">
        <div class="video-info-container">
          <div class="video-info-title">{{ videoDetail.title }}</div>
          <div class="video-info-count">
            <span>
              <i class="video-icon play-icon"></i>
              {{ formatCount(viewCount) }}
            </span>
            <span>
              <i class="video-icon danmu-icon"></i>
              {{ formatCount(danmuCount) }}
            </span>
            <span>
              <i class="video-icon time-icon"></i>
              {{ videoDetail.createTime }}
            </span>
            <span>
              <i class="video-icon prohibit-icon"></i>
              未经作者授权，禁止转载
            </span>
          </div>
        </div>
        <!-- 播放器容器 -->
        <div class="player-container" id="bili-player"></div>

        <!-- 发送弹幕区域 -->
        <div class="danmu-bar">
          <div class="danmu-bar-video-info">
            {{ onlineCount }}人正在看，已装填{{ danmuCount }}条弹幕
          </div>
          <div class="danmu-bar-operation">
            <div class="danmu-bar-sender">
              <div class="danmu-input-wrapper">
                <input
                  class="danmu-bar-sender-input"
                  v-model="danmuText"
                  placeholder="发个友善的弹幕见证当下"
                  autocomplete="off"
                  @keyup.enter="sendDanmu"
                />
              </div>
              <el-button type="primary" class="send-button" @click="sendDanmu">
                发送
              </el-button>
            </div>
          </div>
        </div>

        <!-- 点赞投币收藏栏 -->
        <div class="video-tools-bar">
          <div class="video-tools-bar-left">
            <div
              class="like-coin-collect"
              @click="addOrDeleteLikeCount"
              :class="{ active: isLiked }"
            >
              <img :src="likeIcon" alt="点赞" />
              <span>{{ formatCount(likeCount) }}</span>
            </div>
            <div
              class="like-coin-collect"
              @click="addCoinCount"
              :class="{ active: isCoin }"
            >
              <img :src="coinIcon" alt="投币" />
              <span>{{ formatCount(coinCount) }}</span>
            </div>
            <div
              class="like-coin-collect"
              @click="addOrDeleteCollectCount"
              :class="{ active: isCollect }"
            >
              <img :src="collectIcon" alt="收藏" />
              <span>{{ formatCount(collectCount) }}</span>
            </div>
            <div class="like-coin-collect">
              <img src="@/assets/icons/分享.svg" alt="分享" />
              <span>分享</span>
            </div>
          </div>
        </div>

        <!-- 视频描述和标签 -->
        <div class="left-container-under-player">
          <div class="video-detail-description">
            {{ videoDetail.description }}
          </div>
          <div class="video-detail-tags">
            <el-tag
              v-for="tag in videoDetail.videoTagList"
              :key="tag.tagId"
              type="info"
              class="video-tag"
            >
              {{ tag.tagName }}
            </el-tag>
          </div>
        </div>

        <!-- 评论区 -->
        <VideoComment :videoId="videoId" />
      </div>

      <div class="right-container">
        <!-- UP主信息 -->
        <div class="up-info-container">
          <div class="up-avatar">
            <img :src="videoDetail.avatar || defaultAvatar" alt="UP主头像" />
          </div>
          <div class="up-info-right">
            <div class="up-info-name">{{ videoDetail.nickname }}</div>
            <div class="up-info-fans">粉丝：{{ fansCount }}</div>
          </div>
          <div class="up-operation">
            <el-button
              type="primary"
              :class="{ 'is-followed': isFollowed }"
              @click="toggleFollow"
            >
              {{ isFollowed ? '已关注' : '+ 关注' }}
            </el-button>
          </div>
        </div>

        <!-- 弹幕列表 -->
        <div class="danmu-box">
          <el-collapse v-model="activeNames">
            <el-collapse-item title="弹幕列表" name="1">
              <el-table
                :data="
                  danmuList.sort(
                    (a, b) => new Date(a.createTime) - new Date(b.createTime),
                  )
                "
                style="width: 100%"
                max-height="500"
                :show-overflow-tooltip="false"
              >
                <el-table-column
                  prop="danmuTime"
                  label="时间"
                  class-name="time-column"
                  width="80"
                  :show-overflow-tooltip="false"
                />
                <el-table-column
                  prop="txt"
                  label="弹幕内容"
                  class-name="content-column"
                  min-width="180"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  prop="createTime"
                  label="发送时间"
                  class-name="send-time-column"
                  width="180"
                  :show-overflow-tooltip="false"
                />
              </el-table>
            </el-collapse-item>
          </el-collapse>
        </div>

        <!-- 推荐视频 -->
        <div class="recommend-videos">
          <div
            v-for="video in recommendVideos"
            :key="video.id"
            class="recommend-item"
            @click="goToVideo(video.id)"
          >
            <div class="recommend-cover">
              <img :src="video.cover" alt="视频封面" />
              <span class="recommend-duration">
                {{ formatDuration(video.duration) }}
              </span>
            </div>
            <div class="recommend-info">
              <div class="recommend-video-title">{{ video.title }}</div>
              <div class="recommend-video-uploader">
                <span>{{ video.nickname }}</span>
                <span class="recommend-view-count">
                  <i class="video-icon view-icon"></i>
                  {{ formatViewCount(video.viewCount) }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Player from 'xgplayer'
import Danmu from 'xgplayer/es/plugins/danmu'
import 'xgplayer/es/plugins/danmu/index.css'
import 'xgplayer/dist/index.min.css'
import likeActive from '@/assets/videoicon/dianzan2.png'
import likeInactive from '@/assets/videoicon/dianzan1.png'
import coinActive from '@/assets/videoicon/toubi2.png'
import coinInactive from '@/assets/videoicon/toubi1.png'
import collectActive from '@/assets/videoicon/shoucang2.png'
import collectInactive from '@/assets/videoicon/shoucang1.png'
import defaultAvatar from '@/assets/bilibiliavatar.png'
import VideoComment from '@/components/VideoComment.vue'
// 导入封面图片
import banner1 from '@/assets/anime/images/banner1.png'
import banner2 from '@/assets/anime/images/banner2.png'
import banner3 from '@/assets/anime/images/banner3.png'
import banner4 from '@/assets/anime/images/banner4.png'
import banner5 from '@/assets/anime/images/banner5.png'
import banner6 from '@/assets/anime/images/banner6.png'
import banner7 from '@/assets/anime/images/banner7.png'
import banner8 from '@/assets/anime/images/banner8.png'
import banner9 from '@/assets/anime/images/banner9.png'
import banner10 from '@/assets/anime/images/banner10.png'

const route = useRoute()
const router = useRouter()
const videoId = ref(route.params.id)

// 基础数据
const videoDetail = reactive({
  id: '',
  title: '加载中...',
  createTime: '',
  nickname: '',
  userId: '',
  description: '',
  avatar: '',
  videoUrl: '',
  cover: '',
  videoTagList: [],
})

// 计数器
const viewCount = ref(0)
const danmuCount = ref(0)

const likeCount = ref(0)
const coinCount = ref(0)
const collectCount = ref(0)
const fansCount = ref(0)
const onlineCount = ref(1)

// 状态
const isFollowed = ref(false)
const isLiked = ref(false)
const isCoin = ref(false)
const isCollect = ref(false)
const loading = ref(true)
const activeNames = ref(['1'])
const danmuText = ref('')

// 相关数据
const player = ref(null)
const ws = ref(null)
const danmuList = ref([])
const relatedVideos = ref([])
const recommendVideos = ref([])

// 计算属性 - 图标状态
const likeIcon = computed(() => (isLiked.value ? likeActive : likeInactive))
const coinIcon = computed(() => (isCoin.value ? coinActive : coinInactive))
const collectIcon = computed(() =>
  isCollect.value ? collectActive : collectInactive,
)

// 默认弹幕配置
const defaultDanmuConfig = reactive({
  duration: 5000,
  style: {
    color: '#fff',
    fontSize: '20px',
    padding: '5px 11px',
    border: 'none',
    backgroundColor: 'transparent', // 去除阴影背景
  },
})

// 不同弹幕模式和颜色配置
const danmuModes = [
  { mode: 0, name: '滚动弹幕' }, // 从右到左滚动
  { mode: 1, name: '顶部弹幕' }, // 顶部固定
  { mode: 2, name: '底部弹幕' }, // 底部固定
]

const danmuColors = [
  '#ffffff', // 白色
  '#ff0000', // 红色
  '#00ff00', // 绿色
  '#0000ff', // 蓝色
  '#ffff00', // 黄色
  '#ff00ff', // 粉色
  '#00ffff', // 青色
  '#ffa500', // 橙色
  '#9370db', // 紫色
  '#32cd32', // 绿色
]

// 生命周期
onMounted(() => {
  fetchVideoDetail()
  initWebSocket()
})

onUnmounted(() => {
  if (player.value) {
    player.value.destroy()
  }
  if (ws.value) {
    ws.value.close()
  }
})

// 获取视频详情
const fetchVideoDetail = async () => {
  try {
    // 这里应该调用API获取视频详情
    // const response = await fetch(`/api/video/${videoId.value}`)
    // const data = await response.json()
    // Object.assign(videoDetail, data)

    // 模拟数据
    setTimeout(() => {
      videoDetail.id = videoId.value
      videoDetail.title =
        'bilibili - 高仿B站 Vue3项目实战 easylive 计算机毕业设计 简历项目'
      videoDetail.createTime = '2023-01-01 20:59:56'
      videoDetail.nickname = '程序员老罗'
      videoDetail.userId = 1
      videoDetail.description =
        '这是一个高仿B站的前端项目，使用Vue3+TypeScript开发，适合作为计算机专业的毕业设计或简历项目。\n包含视频播放、弹幕、评论、点赞收藏等核心功能。'
      videoDetail.videoUrl =
        'https://bubble-video.oss-cn-chengdu.aliyuncs.com/bubble/image/c06bce71-037f-468f-be87-fccdd860f40f.mp4'
      videoDetail.videoTagList = [
        { tagId: 1, tagName: 'Vue3' },
        { tagId: 2, tagName: 'TypeScript' },
        { tagId: 3, tagName: '前端' },
        { tagId: 4, tagName: '毕业设计' },
        { tagId: 5, tagName: 'B站' },
      ]

      viewCount.value = 3577
      danmuCount.value = 120
      likeCount.value = 746
      coinCount.value = 480
      collectCount.value = 1988
      fansCount.value = 9600

      loading.value = false

      // 先获取弹幕数据，再初始化播放器
      fetchDanmuList()
      initPlayer()
      fetchRelatedVideos()
      fetchRecommendVideos()
      checkUserInteraction()
    }, 500)
  } catch (error) {
    console.error('Failed to fetch video details:', error)
  }
}

// 初始化播放器
const initPlayer = () => {
  if (!videoDetail.videoUrl) return

  // 将弹幕数据转换为播放器需要的格式
  const comments = danmuList.value.map((item) => {
    // 将时间格式转换为秒数
    const timeParts = item.danmuTime.split(':')
    const seconds = parseInt(timeParts[0]) * 60 + parseInt(timeParts[1])

    return {
      id: Math.random().toString(36).substring(2, 15),
      start: seconds * 1000, // 转换为毫秒
      txt: item.txt,
      duration: defaultDanmuConfig.duration,
      mode: item.mode || 0, // 弹幕模式：0滚动，1顶部固定，2底部固定
      style: {
        ...defaultDanmuConfig.style,
        color: item.color || '#ffffff', // 使用弹幕颜色或默认白色
      },
    }
  })

  player.value = new Player({
    id: 'bili-player',
    url: videoDetail.videoUrl,
    width: '800px',
    height: '450px',
    plugins: [Danmu],
    lang: 'zh',
    pip: true,
    controls: true,
    danmu: {
      comments: comments,
      area: {
        start: 0,
        end: 1,
      },
      fontSize: 22,
      opacity: 1, // 不透明度设为1，让弹幕更清晰
    },
  })

  player.value.danmu.setFontSize(22, 24)

  // 播放结束时增加播放量
  player.value.on('ended', () => {
    viewCount.value++
    // 调用API更新播放量
  })
}

// WebSocket连接
const initWebSocket = () => {
  const token = localStorage.getItem('token')
  if (!token) return

  try {
    const url = `ws://localhost:15005/imserver/${token}`
    ws.value = new WebSocket(url)

    ws.value.onopen = () => {
      console.log('WebSocket connected')
      // 告知服务器当前正在观看的视频
      ws.value.send(
        JSON.stringify({
          type: 'join',
          videoId: videoId.value,
        }),
      )
    }

    ws.value.onmessage = (event) => {
      const data = JSON.parse(event.data)

      // 弹幕消息
      if (data.txt) {
        if (player.value) {
          player.value.danmu.sendComment(data)
        }
        danmuList.value.unshift({
          danmuTime: formatTime(data.start / 1000),
          txt: data.txt,
          createTime: new Date().toLocaleString(),
        })
      }

      // 在线人数更新
      if (data.onlineCount) {
        onlineCount.value = data.onlineCount
      }
    }

    ws.value.onerror = (error) => {
      console.error('WebSocket error:', error)
    }

    ws.value.onclose = () => {
      console.log('WebSocket disconnected')
    }
  } catch (error) {
    console.error('Failed to connect WebSocket:', error)
  }
}

// 发送弹幕
const sendDanmu = () => {
  if (!danmuText.value.trim()) return

  const token = localStorage.getItem('token')
  if (!token) {
    // 提示登录
    return
  }

  if (player.value) {
    const danmuTime = Math.floor(player.value.currentTime * 1000)
    const message = {
      start: danmuTime,
      txt: danmuText.value,
      duration: defaultDanmuConfig.duration,
      style: defaultDanmuConfig.style,
    }

    // 发送弹幕到服务器
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      ws.value.send(
        JSON.stringify({
          type: 'danmu',
          videoId: videoId.value,
          content: message,
          danmuTime: danmuTime,
        }),
      )
    }

    // 本地显示弹幕
    player.value.danmu.sendComment(message)

    // 添加到弹幕列表
    danmuList.value.unshift({
      danmuTime: formatTime(player.value.currentTime),
      txt: danmuText.value,
      createTime: new Date().toLocaleString(),
    })

    danmuText.value = ''
    danmuCount.value++
  }
}

// 获取弹幕列表
const fetchDanmuList = () => {
  // 创建2000条随机弹幕数据，大部分为崩坏星穹铁道内容
  const danmuContents = [
    // 星穹铁道角色相关
    '姬子太帅了！',
    '丹恒，我的丹恒！',
    '卡芙卡我老婆',
    '景元大人好强啊',
    '青雀真可爱',
    '白露我的白露',
    '符玄是真正的强者',
    '银狼天下第一',
    '克拉拉战斗力爆表',
    '瓦尔特也太帅了',
    '刃姐姐冲鸭',
    '三月七的盾真好用',
    '黑塔的debuff无敌',
    '罗刹的战技好强',
    '布洛妮娅boss形态帅炸',
    '希儿真是太可爱了',
    '驭空太飒了',
    '停云的茶太香了',
    '素裳的舞姿真美',
    '桓痕的盔甲帅爆了',
    '镜流剑术无敌',
    '伽罗的普攻好看',
    '霄翰这么强的吗',
    '阿兰太帅了',
    '灵钦我老婆',
    '雪衣仙子',
    '玲可爱到爆炸',

    // 星穹铁道世界观
    '星穹铁道的世界观真精彩',
    '仙舟彼岸太美了',
    '螺丝船已经准备就绪',
    '空间站黑塔好酷',
    '星核真是神奇的东西',
    '星核猎手出发',
    '命途系统设计得太好了',
    '星芒体系复杂又有趣',
    '虚无小队冲鸭',
    '仙舟联盟的科技真发达',
    '开拓者们集合啦',
    '星穹铁道起航',
    '空间站的设计太未来了',
    '星核猎手的责任',
    '开拓者号出发',
    '命途的指引',
    '星穹列车前进',
    '星轨派对开始',
    '迎接星穹铁道的挑战',
    '艾丝妲的信标指引方向',
    '雅利洛-VI的风景太美了',
    '螺旋深渊的挑战',
    '星云商会的秘密',
    '星芒万象的奥秘',
    '新船员报到',

    // 星穹铁道游戏相关
    '满配姬子无敌',
    '丹恒打出10万伤害',
    '这个阵容配合真完美',
    '开局抽到三个五星',
    '终于抽到卡芙卡了',
    '攒了3个月终于抽到星核猎手',
    '这个光锥太适合景元了',
    '混沌记忆副本好难',
    '忘却之庭又更新了',
    '模拟宇宙太好玩了',
    '模拟宇宙8难度通了',
    '星铁周年活动爽爆',
    '宇宙二期太难了',
    '星铁剧情好感人',
    '这版本更新了什么',
    '卡池什么时候复刻',
    '下个版本什么时候',
    '星琼不够抽卡了',
    '体力回复太慢了',
    '这个版本的活动奖励真丰富',
    '这周的周常好难',
    '终于九星螺旋了',
    '清凉出装太帅了',
    '丹恒专武拿到手',
    '等了好久终于复刻了',
    '仙舟试炼攻略求助',
    '这个BOSS好难打',
    '有没有大佬带我刷下材料',
    '这个光锥效果怎么样',
    '命途解析会好玩吗',
    '预约奖励太好了',
    '新角色好帅啊',
    '虚无追溯者出击',

    // 星穹铁道玩家互动
    '有星铁玩家吗？',
    '一起来肝星穹铁道',
    '推荐个星铁阵容',
    '适合卡芙卡的光锥',
    '星铁今天更新了',
    '有没有人一起玩星铁',
    '今天忘却之庭更新了',
    '星铁2.0爆肝中',
    '谁有丹恒攻略',
    '银狼怎么配队',
    '星铁玩家报道',
    '开拓者出征',
    '星铁真好玩',
    '有人看直播抽卡吗',
    '星铁真是越玩越上头',
    '刚入坑求带',
    '哪位大佬有景元账号',
    '今天抽卡居然出了姬子',
    '米哈游yyds',
    '星铁的音乐太好听了',
    '这bgm真洗脑',
    '好喜欢三月七的配音',
    '开拓者宿舍真好看',
    '仙舟联盟的剧情太牛了',
    '星穹铁道的任务好有意思',
    '这次更新的内容好多',
    '新地图好大啊',
    '罗浮安什么时候开',
    '雅利洛-VI的雪景太美了',
    '最爱星穹铁道的开场动画',

    // 一些原有的弹幕内容，保留少量
    '这个视频太棒了！',
    '前排占座',
    '学到了很多，感谢UP主',
    '求源码地址',
    'B站风格做得真像',
    'Vue3好用，但是学起来有点难',
    '这种弹幕效果是怎么做的？',
    '弹幕设计得不错',
    '弹幕满屏飞真好看',
    '彩色弹幕真漂亮',
    '底部弹幕是怎么做的',
    '前端加油！',
    '弹幕功能好难做啊',
    '前端真有趣',
    '这个效果我得学学',
    '滚动好流畅',
  ]

  const danmus = []
  for (let i = 0; i < 2000; i++) {
    // 随机弹幕内容
    const contentIndex = Math.floor(Math.random() * danmuContents.length)
    const content = danmuContents[contentIndex]

    // 随机时间点，视频假设10分钟长
    const randomTime = Math.random() * 600

    // 随机弹幕模式：80%滚动弹幕，10%顶部固定，10%底部固定
    const randomModeIndex =
      Math.random() < 0.8 ? 0 : Math.random() < 0.5 ? 1 : 2
    const mode = danmuModes[randomModeIndex].mode

    // 随机颜色：60%白色，40%彩色
    const randomColorIndex =
      Math.random() < 0.6 ? 0 : Math.floor(Math.random() * danmuColors.length)
    const color = danmuColors[randomColorIndex]

    // 创建随机的历史时间
    const date = new Date()
    date.setMinutes(date.getMinutes() - Math.floor(Math.random() * 60 * 24 * 7)) // 最近一周内

    danmus.push({
      danmuTime: formatTime(randomTime),
      txt: content,
      createTime: date.toLocaleString(),
      mode: mode,
      color: color,
    })
  }

  // 按时间排序
  danmus.sort((a, b) => {
    const timeA = a.danmuTime
      .split(':')
      .reduce((acc, val, i) => acc + parseInt(val) * (i === 0 ? 60 : 1), 0)
    const timeB = b.danmuTime
      .split(':')
      .reduce((acc, val, i) => acc + parseInt(val) * (i === 0 ? 60 : 1), 0)
    return timeA - timeB
  })

  danmuList.value = danmus

  // 更新弹幕数量
  danmuCount.value = 2000
}

// 获取相关视频（选集）
const fetchRelatedVideos = () => {
  // 模拟数据
  relatedVideos.value = Array(8)
    .fill(0)
    .map((_, index) => ({
      id: String(index + 1),
      title: `第${index + 1}集：Vue3项目实战课程`,
      duration: 1800 + index * 300,
    }))
}

// 获取推荐视频
const fetchRecommendVideos = () => {
  // 模拟数据 - 改为二次元内容
  const animeCovers = [
    banner1,
    banner2,
    banner3,
    banner4,
    banner5,
    banner6,
    banner7,
    banner8,
    banner9,
    banner10,
  ]

  const animeTitles = [
    '【星穹铁道】开拓者姬子角色展示',
    '【原神】须弥主线任务攻略：仙舟漂流记',
    '【崩坏3】终焉律者角色实战演示',
    '【Fate/GO】山中老人百貌实装测评',
    '【鬼灭之刃】无限列车篇精彩剪辑',
    '【进击的巨人】最终季高能名场面混剪',
    '【JOJO的奇妙冒险】荒木飞彦艺术风格解析',
    '【OVERLORD】安兹乌尔恭的骨王形态技能展示',
    '【Re:从零开始的异世界生活】雷姆角色歌',
    '【蔚蓝档案】未花学院日常搞笑时刻',
  ]

  const animeUploaders = [
    '米哈游官方',
    '崩坏学园',
    '型月工作室',
    '鬼灭之刃中文官方',
    '进击的巨人FANS',
    'JOJO爱好者',
    'OVERLORD骨王后援会',
    'Re0字幕组',
    '蔚蓝档案玩家',
    '二次元爱好者联盟',
  ]

  recommendVideos.value = Array(10)
    .fill(0)
    .map((_, index) => ({
      id: String(100 + index),
      title: animeTitles[index],
      cover: animeCovers[index],
      duration: 1200 + index * 600,
      nickname: animeUploaders[index],
      viewCount: Math.floor(Math.random() * 100000),
    }))
}

// 检查用户交互状态（点赞、投币、收藏、关注）
const checkUserInteraction = () => {
  const token = localStorage.getItem('token')
  if (!token) return

  // 模拟数据
  isLiked.value = false
  isCoin.value = false
  isCollect.value = false
  isFollowed.value = false
}

// 切换关注状态
const toggleFollow = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    // 提示登录
    return
  }

  isFollowed.value = !isFollowed.value
  // 调用API更新关注状态
}

// 点赞/取消点赞
const addOrDeleteLikeCount = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    // 提示登录
    return
  }

  isLiked.value = !isLiked.value
  likeCount.value += isLiked.value ? 1 : -1
  // 调用API更新点赞状态
}

// 投币
const addCoinCount = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    // 提示登录
    return
  }

  if (!isCoin.value) {
    isCoin.value = true
    coinCount.value += 1
    // 调用API更新投币状态
  }
}

// 收藏/取消收藏
const addOrDeleteCollectCount = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    // 提示登录
    return
  }

  isCollect.value = !isCollect.value
  collectCount.value += isCollect.value ? 1 : -1
  // 调用API更新收藏状态
}

// 跳转到其他视频
const goToVideo = (id) => {
  router.push(`/video/detail/${id}`)
}

// 切换选集
const changeVideo = (id) => {
  if (id !== videoId.value) {
    videoId.value = id
    fetchVideoDetail()
  }
}

// 格式化视频时长
const formatDuration = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 格式化播放时间点
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 格式化播放量
const formatViewCount = (count) => {
  if (count >= 10000) {
    return (count / 10000).toFixed(1) + '万'
  }
  return count
}

// 格式化计数
const formatCount = (count) => {
  if (count >= 10000) {
    return (count / 10000).toFixed(1) + '万'
  }
  return count
}
</script>

<style scoped lang="scss">
.video-detail-container {
  padding-top: 15px;
  background-color: #fffafa;
  min-height: 100vh;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url('@/assets/icons/pattern.svg');
    background-size: 200px;
    opacity: 0.05;
    z-index: 0;
    pointer-events: none;
  }

  .video-main {
    display: flex;
    width: 1280px;
    margin: 0 auto;
    gap: 20px;
    padding: 0 0 0 40px;
    position: relative;
    z-index: 1;

    .left-container {
      flex: 1;
      min-width: 820px;
      max-width: 840px;
      background: transparent;
      border-radius: 0;
      padding: 0;
      box-shadow: none;

      .video-info-container {
        margin-bottom: 15px;
        background-color: #ffffff;
        border-radius: 16px;
        padding: 16px;
        box-shadow: 0 4px 10px rgba(220, 120, 120, 0.1);
        transition: all 0.3s ease;
        border: 1px solid rgba(240, 100, 100, 0.15);

        &:hover {
          transform: translateY(-3px);
          box-shadow: 0 6px 15px rgba(220, 120, 120, 0.15);
        }

        .video-info-title {
          font-size: 22px;
          font-weight: 600;
          margin-bottom: 12px;
          line-height: 1.4;
          color: #fb7299;
          text-shadow: 0 1px 2px rgba(251, 114, 153, 0.1);
        }

        .video-info-count {
          display: flex;
          align-items: center;
          color: #c486a1;
          font-size: 13px;
          flex-wrap: wrap;
          gap: 14px;

          span {
            display: flex;
            align-items: center;
            position: relative;

            &:hover {
              color: #fb7299;
            }

            img,
            i {
              width: 16px;
              height: 16px;
              margin-right: 6px;
              opacity: 0.8;
              transition: transform 0.3s;

              &:hover {
                transform: scale(1.2);
              }
            }

            .video-icon {
              display: inline-block;
              width: 16px;
              height: 16px;
              margin-right: 6px;
              opacity: 0.8;
              transition: transform 0.3s;

              &:hover {
                transform: scale(1.2);
              }
            }

            .play-icon {
              background: url('@/assets/icons-new/play-icon.svg') no-repeat
                center;
              background-size: cover;
            }

            .danmu-icon {
              background: url('@/assets/icons-new/danmu-icon.svg') no-repeat
                center;
              background-size: cover;
            }

            .time-icon {
              background: url('@/assets/icons-new/time-icon.svg') no-repeat
                center;
              background-size: cover;
            }

            .prohibit-icon {
              background: url('@/assets/icons-new/prohibit-icon.svg') no-repeat
                center;
              background-size: cover;
            }
          }
        }
      }

      .player-container {
        width: 100%;
        height: 530px;
        background-color: #000;
        margin-bottom: 15px;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 8px 16px rgba(220, 120, 120, 0.15);
        border: 3px solid #ffffff;
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 12px 20px rgba(220, 120, 120, 0.2);
        }
      }

      .danmu-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 36px;
        padding: 0;
        margin-bottom: 15px;
        background: transparent;
        width: 100%;
        position: relative;

        .danmu-bar-video-info {
          font-size: 13px;
          color: #c486a1;
          display: flex;
          align-items: center;
          gap: 6px;

          img,
          i {
            width: 14px;
            height: 14px;
          }

          .online-icon {
            display: inline-block;
            width: 14px;
            height: 14px;
            background: url('@/assets/icons-new/online-icon.svg') no-repeat
              center;
            background-size: cover;
            opacity: 0.8;
          }
        }

        .danmu-bar-operation {
          display: flex;
          height: 100%;
          flex: 1;
          margin-left: 12px;
          max-width: calc(100% - 200px);
          position: relative;

          .danmu-bar-sender {
            display: flex;
            width: 100%;
            align-items: center;
            gap: 0;

            .danmu-input-wrapper {
              flex: 1;
              display: flex;
              align-items: center;
              background: #ffeef1;
              border-radius: 18px 0 0 18px;
              padding: 6px 12px;
              margin-right: 0;
              border: 1px solid rgba(240, 100, 100, 0.15);
              border-right: none;
              transition: all 0.3s;

              &:focus-within {
                background: #fff5f7;
                border-color: #fb7299;
              }

              .danmu-bar-sender-input {
                flex: 1;
                border: none;
                outline: none;
                font-size: 13px;
                background: transparent;
                color: #fb7299;

                &::placeholder {
                  color: #d0a0b0;
                }

                &:focus {
                  border-color: #fb7299;
                }
              }
            }

            .send-button {
              height: 36px;
              padding: 0 15px;
              background: #fb7299;
              border: none;
              border-radius: 0 18px 18px 0;
              font-size: 13px;
              color: #fff;
              transition: all 0.3s;
              box-shadow: 0 3px 6px rgba(251, 114, 153, 0.2);

              &:hover {
                background: #fc8bab;
                transform: translateY(-2px);
                box-shadow: 0 5px 10px rgba(251, 114, 153, 0.25);
              }

              &:active {
                transform: translateY(0);
                box-shadow: 0 2px 4px rgba(251, 114, 153, 0.15);
              }
            }
          }
        }
      }

      .video-tools-bar {
        display: flex;
        padding: 16px;
        margin-bottom: 16px;
        background-color: #ffffff;
        border-radius: 16px;
        box-shadow: 0 4px 10px rgba(220, 120, 120, 0.1);
        border: 1px solid rgba(240, 100, 100, 0.15);

        .video-tools-bar-left {
          display: flex;
          align-items: center;
          gap: 25px;

          .like-coin-collect {
            display: flex;
            align-items: center;
            cursor: pointer;
            color: #c486a1;
            font-size: 14px;
            transition: all 0.3s;
            padding: 5px 10px;
            border-radius: 12px;
            background-color: rgba(255, 240, 245, 0.5);

            &:hover {
              color: #fb7299;
              background-color: rgba(251, 114, 153, 0.1);
              transform: translateY(-2px);
            }

            &.active {
              color: #fb7299;
              background-color: rgba(251, 114, 153, 0.15);
            }

            img {
              margin-right: 6px;
              height: 24px;
              width: 24px;
              opacity: 0.8;
              transition: all 0.3s;

              &:hover {
                opacity: 1;
                transform: scale(1.1);
              }
            }
          }
        }
      }

      .left-container-under-player {
        margin-bottom: 20px;
        background-color: #ffffff;
        border-radius: 16px;
        padding: 16px;
        box-shadow: 0 4px 10px rgba(220, 120, 120, 0.1);
        border: 1px solid rgba(240, 100, 100, 0.15);

        .video-detail-description {
          font-size: 14px;
          color: #7f5f69;
          line-height: 1.8;
          white-space: pre-wrap;
          margin-bottom: 15px;
          padding: 12px;
          background-color: #fff5f7;
          border-radius: 12px;
          border: 1px solid rgba(240, 100, 100, 0.1);
        }

        .video-detail-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          padding: 5px;

          .video-tag {
            padding: 4px 12px;
            border-radius: 12px;
            background-color: #fff0f3;
            color: #fb7299;
            cursor: pointer;
            transition: all 0.3s;
            border: 1px solid rgba(251, 114, 153, 0.2);

            &:hover {
              background-color: #ffecf0;
              color: #fc5286;
              transform: translateY(-2px);
              box-shadow: 0 3px 6px rgba(251, 114, 153, 0.15);
            }
          }
        }
      }
    }

    .right-container {
      width: 400px;
      flex-shrink: 0;

      .up-info-container {
        background-color: #ffffff;
        padding: 16px;
        margin-bottom: 16px;
        border-radius: 16px;
        display: flex;
        align-items: center;
        gap: 12px;
        box-shadow: 0 4px 10px rgba(220, 120, 120, 0.1);
        border: 1px solid rgba(240, 100, 100, 0.15);
        transition: all 0.3s;

        &:hover {
          transform: translateY(-3px);
          box-shadow: 0 6px 15px rgba(220, 120, 120, 0.15);
        }

        .up-avatar {
          width: 54px;
          height: 54px;
          border-radius: 50%;
          overflow: hidden;
          border: 3px solid #ffe6eb;
          box-shadow: 0 3px 8px rgba(220, 120, 120, 0.15);
          transition: all 0.3s;

          &:hover {
            transform: scale(1.05) rotate(5deg);
          }

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .up-info-right {
          flex: 1;

          .up-info-name {
            font-size: 16px;
            font-weight: 600;
            color: #fb7299;
            margin-bottom: 6px;
            text-shadow: 0 1px 2px rgba(251, 114, 153, 0.1);
          }

          .up-info-fans {
            font-size: 13px;
            color: #c486a1;
            display: inline-block;
            padding: 2px 8px;
            background-color: #fff0f3;
            border-radius: 10px;
          }
        }

        .up-operation {
          .el-button {
            width: 95px;
            height: 36px;
            font-size: 14px;
            border-radius: 18px;
            background-color: #fb7299;
            border-color: #fb7299;
            color: #fff;
            box-shadow: 0 3px 6px rgba(251, 114, 153, 0.2);
            transition: all 0.3s;

            &.is-followed {
              background-color: #fff;
              color: #fb7299;
              border-color: #fab1c0;
            }

            &:hover {
              background-color: #fc8bab;
              border-color: #fc8bab;
              transform: translateY(-2px);
              box-shadow: 0 5px 10px rgba(251, 114, 153, 0.25);

              &.is-followed {
                background-color: #fff5f7;
                color: #fc8bab;
                border-color: #ffc9d3;
              }
            }
          }
        }
      }

      .danmu-box {
        background-color: #ffffff;
        margin-bottom: 16px;
        border-radius: 16px;
        box-shadow: 0 4px 10px rgba(220, 120, 120, 0.1);
        border: 1px solid rgba(240, 100, 100, 0.15);
        padding: 12px;

        :deep(.el-collapse) {
          border: none;
        }

        :deep(.el-collapse-item__header) {
          font-size: 15px;
          font-weight: 500;
          color: #fb7299;
          padding: 8px 12px;
          background: #fff5f7;
          border: none;
          height: 40px;
          line-height: 24px;
          margin-bottom: 1px;
          border-radius: 8px;
          position: relative;

          &::after {
            content: '✨';
            position: absolute;
            right: 40px;
            font-size: 14px;
          }
        }

        :deep(.el-collapse-item__content) {
          padding: 10px 0;
        }

        :deep(.el-table) {
          font-size: 13px;
          background: transparent;

          &::before,
          &::after {
            display: none;
          }

          th {
            background: #fff5f7;
            color: #fb7299;
            font-weight: 500;
            border: none;
            padding: 8px 12px;
            line-height: 1.5;
          }

          td {
            color: #7f5f69;
            border: none;
            padding: 8px 12px;
            line-height: 1.5;

            &.time-column {
              color: #c486a1;
            }
          }

          tr {
            background: transparent;
            transition: all 0.3s;

            &:hover {
              background: #fff0f3;

              td.content-column {
                color: #fb7299;
              }
            }
          }

          .time-column {
            width: 80px;
            color: #c486a1;
            white-space: nowrap;
            overflow: visible;
          }

          .content-column {
            min-width: 180px;
            padding-right: 16px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .send-time-column {
            width: 180px;
            color: #c486a1;
            white-space: nowrap;
            overflow: visible;
          }
        }
      }

      .recommend-videos {
        background-color: #ffffff;
        border-radius: 16px;
        padding: 16px;
        box-shadow: 0 4px 10px rgba(220, 120, 120, 0.1);
        border: 1px solid rgba(240, 100, 100, 0.15);

        .recommend-item {
          display: flex;
          margin-bottom: 12px;
          padding-bottom: 12px;
          border-bottom: 1px solid #fff0f3;
          cursor: pointer;
          transition: all 0.3s;

          &:last-child {
            margin-bottom: 0;
            padding-bottom: 0;
            border-bottom: none;
          }

          &:hover {
            transform: translateX(5px);

            .recommend-video-title {
              color: #fb7299;
            }

            .recommend-cover img {
              transform: scale(1.05);
            }
          }

          .recommend-cover {
            position: relative;
            width: 170px;
            height: 96px;
            border-radius: 12px;
            overflow: hidden;
            border: 2px solid #ffe6eb;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
              transition: all 0.3s;
            }

            .recommend-duration {
              position: absolute;
              bottom: 4px;
              right: 4px;
              background: rgba(0, 0, 0, 0.7);
              color: #fff;
              padding: 2px 6px;
              border-radius: 8px;
              font-size: 12px;
            }
          }

          .recommend-info {
            flex: 1;
            padding-left: 12px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .recommend-video-title {
              font-size: 14px;
              line-height: 1.4;
              margin-bottom: 8px;
              color: #7f5f69;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
              overflow: hidden;
              transition: all 0.3s;
            }

            .recommend-video-uploader {
              font-size: 12px;
              color: #c486a1;
              display: flex;
              align-items: center;

              .recommend-view-count {
                margin-left: 12px;
                display: flex;
                align-items: center;

                i {
                  margin-right: 4px;
                  font-size: 14px;
                }

                .view-icon {
                  display: inline-block;
                  width: 14px;
                  height: 14px;
                  background: url('@/assets/icons-new/view-icon.svg') no-repeat
                    center;
                  background-size: cover;
                  opacity: 0.8;
                  margin-right: 4px;
                }
              }
            }
          }
        }
      }
    }
  }
}

// 设置弹幕表格行高，确保只占一行
:deep(.el-table__row) {
  height: 32px;
  line-height: 32px;
}

:deep(.el-table__cell) {
  padding-top: 4px;
  padding-bottom: 4px;
}

:deep(.danmu-box .el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

// 媒体查询
@media (max-width: 1280px) {
  .video-detail-container {
    .video-main {
      width: 100%;
      padding: 0 20px;
      flex-direction: column;

      .left-container {
        min-width: auto;
        max-width: 100%;
      }

      .right-container {
        width: 100%;
      }
    }
  }
}
</style>
